package com.ziyun.erp.modules.member.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ziyun.erp.modules.erpUserLog.entity.ErpUserLogEntity;
import com.ziyun.erp.modules.erpUserLog.service.ErpUserLogService;
import com.ziyun.erp.modules.member.dao.ConfigMemberLevelDao;
import com.ziyun.erp.modules.member.entity.ConfigMemberLevelEntity;
import com.ziyun.erp.modules.member.service.ConfigMemberLevelService;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.common.utils.R;
import io.renren.modules.sys.entity.SysUserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;


@Service("configMemberLevelService")
public class ConfigMemberLevelServiceImpl extends ServiceImpl<ConfigMemberLevelDao, ConfigMemberLevelEntity> implements ConfigMemberLevelService {

    @Autowired
    private ConfigMemberLevelDao configMemberLevelDao;
    @Autowired
    private ErpUserLogService erpUserLogService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Page<ConfigMemberLevelEntity> page = this.selectPage(
                new Query<ConfigMemberLevelEntity>(params).getPage(),
                new EntityWrapper<ConfigMemberLevelEntity>().eq("disabled","false")
        );

        return new PageUtils(page);
    }

    @Transactional(readOnly = false)
    public Map<String, Object> setDefault(Integer memberLvId) {
        Map<String, Object> map = new HashMap<String, Object>();
        int res = 0;
        res = configMemberLevelDao.updateDefault();
        if (res > 0) {
            res = configMemberLevelDao.setDefault(memberLvId);
            if (res > 0) {
                map.put("code", res);
                map.put("msg", "设置默认值成功！");
            } else {
                map.put("code", res);
                map.put("msg", "设置默认值失败！");
            }
        } else {
            map.put("code", res);
            map.put("msg", "修改默认值失败！");
        }
        return map;
    }

    @Override
    @Transactional(readOnly = false)
    public R deleteByIds(Integer[] memberLvIds,SysUserEntity curentUser) {
        ErpUserLogEntity erpUserLogEntity = new ErpUserLogEntity();
        erpUserLogEntity.setUserId(curentUser.getUserId().intValue());
        erpUserLogEntity.setCreateBy(curentUser.getUsername());

        int i = configMemberLevelDao.deleteByIds(memberLvIds);
        if (i <= 0) {
            return R.error("删除失败");
        }
        //记录操作日志
        erpUserLogEntity.setLog("会员等级删除:会员ID(" +curentUser.getUserId() + ")删除" + memberLvIds.toString());
        erpUserLogService.insert(erpUserLogEntity);
        return R.ok();
    }

}
